

%% data and voting-stage estimates

load('voting_stage.mat')

% baseline specification
D = D(:,length(rfe)+(1:length(dnames)));
KD = size(D,2);
Z = X0; % campaign-stage instruments
KZ = size(Z,2);
B = B0(1:end-2);
cmax = - B(end-1) / (2 * B(end));

% Knitro options
optCS = optimset('Display','off');
    

%% 2-step GMM

% first iteration
W = eye(KZ);
[gamma,~,exit_cs1] = knitro_nlp(@(th)Q_cs(th,B,X0,C,Z,xi0,[N0,N1,N2],optCS,cmax,W),...
    [5.4;2.94;2.95;5.6;4.4],[],[],[],[],[],[],[],[],optCS,'knitro2.opt');

% second iteration
[~,br,~] = Q_cs(gamma,B,X0,C,Z,xi0,[N0,N1,N2],optCS,cmax,W);
br = C - br;
W = Z' * diag(br.*br) * Z; % optimal weighting matrix
[gamma,~,exit_cs2] = knitro_nlp(@(th)Q_cs(th,B,X0,C,Z,xi0,[N0,N1,N2],optCS,cmax,W),...
    gamma,[],[],[],[],[],[],[],[],optCS,'knitro2.opt');


%% robust inference (accounting for voting-stage estimation uncertainty)

% gradient of moment conditions (central finite differences)
load('campaign_stage.mat','Ghat00') % for "short" replication
% Ghat00 = grad_cs_moments(gamma,B,X0,C,xi0,Z,KD,[N0,N1,N2],optCS,cmax,1e-4); % for "long" replication, uncomment this line

% joint covariance matrix (voting and campaign stages)
[~,br0,~] = Q_cs(gamma,B,X0,C,Z,xi0,[N0,N1,N2],optCS,cmax,W);
br = C - br0;
Omega = [Z' * diag(br.*br) * Z,Z' * diag(br.*xi0) * Z0;(Z' * diag(br.*xi0) * Z0)',Z0' * diag(xi0.*xi0) * Z0];
Ghat = [Ghat00;zeros(size(Z0,2),length(gamma)),Ghat0(:,1:end-2)];
VgammaBeta = inv(Ghat' * (Omega \ Ghat));
seGamma = sqrt(diag(VgammaBeta));
seGamma = seGamma(1:length(gamma));
rGamma = [gamma,seGamma,2*(1-normcdf(abs(gamma./seGamma)))];

disp(' ')
disp('for Table 5:')
disp(print_results_gamma(round(rGamma,3)))


%%

clearvars -except dnames D KD Z KZ X0 B B0 cmax optCS W ...
    gamma exit_cs1 exit_cs2 br0 Ghat Ghat00 Omega VgammaBeta seGamma rGamma

save('campaign_stage.mat')



